package com.example.myapplication.util

import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream

/**
 * @author Niu
 * @date 2025-08-17
 */
object HttpUtils {

    private val client = OkHttpClient()

    // get请求
    fun get(url: String): String {
        val request = Request.Builder().url(url).build()
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                throw Exception("Unexpected code ${response.code},message ${response.message}")
            }
            val body = response.body?.string() ?: throw Exception("Response body is null")
            return body
        }
    }

    fun downloadImage(url: String, outputPath: String) {
        val client = OkHttpClient()
        val request = Request.Builder().url(url).build()
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) throw Exception("Failed to download image: ${response.code}")
            val bytes = response.body?.bytes() ?: throw Exception("Image download failed, no body.")
            val file = File(outputPath)
            if (!file.parentFile.exists()) {
                file.parentFile.mkdirs()
            }
            println("文件路径：${file.absolutePath}")
            FileOutputStream(file).use { fos ->
                fos.write(bytes)
                fos.flush()
            }
        }
    }

}